package leetcode_题库;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/8/20 13:52
 */
public class _876_链表的中间结点 {


    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(6);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        System.err.println(middleNode(head).val);
    }

    public static ListNode middleNode(ListNode head) {
        //寻找链表的中间点，快慢指针是最方便、最高效的办法。
        ListNode fast = head,slow = head;
        while (fast != null && fast.next !=null){
            fast = fast.next.next;
            slow = slow.next;
        }
        //当快指针走到尽头，慢指针一定在中间位置
        return slow;
        /*
            【mine】
            > 2022/08/20 14:09:23
            解答成功:
                执行耗时:0 ms,击败了100.00% 的Java用户
                内存消耗:38.8 MB,击败了84.90% 的Java用户

         */
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

}


